package com.lh.music.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lh.music.PlayApplication;
import com.lh.music.R;
import com.lh.music.adapter.SongDetailAdapter;
import com.lh.music.constant.Constants;
import com.lh.music.dao.SongDao;
import com.lh.music.entity.Song;

import java.sql.SQLException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SongDetailActivity extends BaseActivity implements SongDetailAdapter.OnMoreClickListener{
    private ListView listView;
    private List<Song> mData;
    private TextView artist,search;
    private SongDetailAdapter adapter;
    private Timer updateListTimer;
    private PopupWindow window;
    String flag;
    private SongDao dao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_singer_detail);
        initView();
        dao=new SongDao(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent broadIntent = new Intent();
             /*   Bundle bundle = new Bundle();
                ArrayList songList = (ArrayList) mData;
                bundle.putSerializable("songList", songList);
                broadIntent.putExtra("bundle", bundle);*/
                app.currentSongList.clear();
                app.currentSongList.addAll(mData);
                //更新数据库中当前播放的列表
                try {
                    dao.updatePlaySongList(app.currentSongList);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                broadIntent.putExtra("position", position);
                broadIntent.setAction(Constants.PLAY_ACTION);
                sendBroadcast(broadIntent);
            }
        });
        timerUpdateListView();
    }

    private void initView() {
        listView= (ListView) findViewById(R.id.listView);
        artist= (TextView) findViewById(R.id.artist);
        search= (TextView) findViewById(R.id.search);
        Bundle bundle=getIntent().getBundleExtra("bundle");
        flag=getIntent().getStringExtra("flag");
        mData= (List<Song>) bundle.getSerializable("songList");

        if (flag.equals("singer")){
            artist.setText(mData.get(0).getArtist());
            search.setText("查看歌手页");
        }else if(flag.equals("album")){
            artist.setText(mData.get(0).getAlbum());
            search.setText("查看专辑页");
        }else if (flag.equals("favorate")){
            artist.setText("我喜欢听");
            search.setText("清空全部");
        }
        adapter=new SongDetailAdapter(this,mData);
        listView.setAdapter(adapter);
        adapter.setOnMoreClickListener(this);
    }
    //将布局添加到父窗口中

    @Override
    public View getChildContentView() {
        return getLayoutInflater().inflate(R.layout.activity_singer_detail,null);
    }
    protected Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what==1){
                updateListView();
            }
        }
    };
    private void timerUpdateListView(){
        updateListTimer=new Timer();
        updateListTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg=handler.obtainMessage();
                msg.what=1;
                handler.sendMessage(msg);
            }
        },0,400);
    }
    private void updateListView(){
        PlayApplication app= (PlayApplication) getApplication();

        for (int i=0;i<mData.size();i++){
            mData.get(i).setVisiable(false);
            //如果这首歌和正在播放的歌一样   该项显示小喇叭
            if (app.currentSong!=null){
                if (mData.get(i).getTitle().equals(app.currentSong.getTitle())){
                    mData.get(i).setVisiable(true);
                }
            }

        }
        adapter.notifyDataSetChanged();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        updateListTimer.cancel();
    }

    @Override
    public void onMoreClickListener(Song song) {
        backgroundAlpha(0.4f);
        //弹出popupwindow
        initPopupWindow(song);
    }
    private void initPopupWindow(Song song) {
        View popupView= LayoutInflater.from(this)
                .inflate(R.layout.popup_song,null);
        window=new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT );
        //更新window中的值
        updatePopupView(popupView,song);
        window.setFocusable(true);
        window.setOutsideTouchable(true);
        ColorDrawable colorDrawable=new ColorDrawable(0);
        window.setBackgroundDrawable(colorDrawable);
        //window消失之后的监听
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
        window.setAnimationStyle(R.style.popup_anim);
        //获取屏幕的高度   显示矩阵对象
        DisplayMetrics dm=new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);  //拿到屏幕的信息


        window.showAtLocation(popupView, Gravity.NO_GRAVITY,
                0,
                dm.heightPixels-popupView.getHeight());
    }
    private void updatePopupView(View popupView, final Song song) {
        TextView song_name= (TextView) popupView.findViewById(R.id.song_name);
        TextView artist_name= (TextView) popupView.findViewById(R.id.artist_name);
        TextView album_name= (TextView) popupView.findViewById(R.id.album_name);
        TextView add= (TextView) popupView.findViewById(R.id.add);
        song_name.setText("歌曲："+song.getTitle());
        artist_name.setText("歌手："+song.getArtist());
        album_name.setText("专辑："+song.getAlbum());
        if (flag.equals("favorate")){
            add.setText("移除我喜欢");
        }else {
            add.setText("添加到我喜欢");
        }
        //将这首歌添加到我喜欢
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //移除我喜欢
                if (flag.equals("favorate")){
                    try {
                        boolean res=dao.updateSongNotIsFavorate(song);
                        mData.clear();
                        mData.addAll(dao.findAllFavorateSong());
                        adapter.notifyDataSetChanged();
                        if (res){
                            Toast.makeText(app, "移除成功", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(app, "移除失败", Toast.LENGTH_SHORT).show();
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }//添加到我喜欢
                else{

                    boolean i= false;
                    try {
                        i = dao.updateSongIsFavorate(song);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    if (i){
                        Toast.makeText(SongDetailActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(SongDetailActivity.this, "歌曲已经存在", Toast.LENGTH_SHORT).show();

                    }
                }

                window.dismiss();
            }
        });
    }
    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
}
